You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.

Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline

Fused activation function: combines Hardswish and Sigmoid (gate)

Element-wise parallelization using CUDA grid-stride loops

Numerically stable sigmoid implementation (separated positive/negative cases)

Memory-efficient in-place-like computation with torch.empty_like

Contiguous tensor handling for performance

Auto-tuning block/grid size based on tensor size (up to 65535 blocks)



Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
import torch
import torch.nn as nn
import torch.nn.functional as F


class Model(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        hard_swish = x * F.relu6(x + 3) / 6
        gate = torch.sigmoid(x)
        return hard_swish * gate


batch_size = 128
feature_dim = 512


def get_inputs():
    x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
    return [x]


def get_init_inputs():
    return []